import useRequest from "@/api/useRequest";

export class sdControllerApi {

  static async generateText2ImgAndCheck(data: any, timeoutMs: number): Promise<any> {
    try {
      // 发送任务提交请求
      const response = await useRequest({
        url: "/stableDiffusionTask/submitTxt2ImgTask",
        method: "post",
        data,
      });
      const taskId = response.data.result;
      let pollingInterval;
      let polling = true; // 添加一个轮询标志变量
      const pollTaskStatus = async () => {
        console.log('pollTaskStatus{}检查状态')
        try {

          if (!polling) {
            // 如果轮询被标志为停止，则返回 null
            return null;
          }
          // 发送任务状态检查请求
          const statusResponse = await useRequest({
            url: "/gps/sdTask/" + taskId + "/fetch",
            method: "get",
          });
          const status = statusResponse.data.taskStatus;
          console.log("status", status);
          if (status === "NOT_START" || status === "SUBMITTED" || status === "IN_PROGRESS") {
            // 继续轮询
            await new Promise(resolve => setTimeout(resolve, 5000)); // 等待5秒
            return pollTaskStatus(); // 继续轮询
          } else {
            clearInterval(pollingInterval);
            if (status === "SUCCESS") {
              console.log(statusResponse);
              // 返回任务制作成功的结果
              return statusResponse.data;
            } else {
              // 返回任务制作失败的结果
              throw new Error("任务制作失败");
            }
          }
        } catch (error) {
          throw new Error("任务状态检查失败");
        }
      };

      // 使用 Promise.race 来同时等待任务完成和超时时间的先发生
      const result = await Promise.race([
        pollTaskStatus(),
        new Promise((_, reject) => {
          setTimeout(() => {
            clearInterval(pollingInterval)
            polling = false
            reject(new Error("任务超时"));
          }, timeoutMs);
        }),
      ]);
      console.log('result:{}', result)
      return result;
    } catch (error) {
      throw new Error("提交任务失败");
    }
  }


  static async generateImg2ImgAndCheck(data: any, timeoutMs: number): Promise<any> {
    try {
      // 发送任务提交请求
      const response = await useRequest({
        url: "/stableDiffusionTask/submitImg2ImgTask",
        method: "post",
        data,
      });
      const taskId = response.data.result;
      let pollingInterval;
      let polling = true; // 添加一个轮询标志变量
      const pollTaskStatus = async () => {
        console.log('pollTaskStatus{}检查状态')
        try {

          if (!polling) {
            // 如果轮询被标志为停止，则返回 null
            return null;
          }
          // 发送任务状态检查请求
          const statusResponse = await useRequest({
            url: "/gps/sdTask/" + taskId + "/fetch",
            method: "get",
          });
          const status = statusResponse.data.taskStatus;
          console.log("status", status);
          if (status === "NOT_START" || status === "SUBMITTED" || status === "IN_PROGRESS") {
            // 继续轮询
            await new Promise(resolve => setTimeout(resolve, 5000)); // 等待5秒
            return pollTaskStatus(); // 继续轮询
          } else {
            clearInterval(pollingInterval);
            if (status === "SUCCESS") {
              console.log(statusResponse);
              // 返回任务制作成功的结果
              return statusResponse.data;
            } else {
              // 返回任务制作失败的结果
              throw new Error("任务制作失败");
            }
          }
        } catch (error) {
          throw new Error("任务状态检查失败");
        }
      };

      // 使用 Promise.race 来同时等待任务完成和超时时间的先发生
      const result = await Promise.race([
        pollTaskStatus(),
        new Promise((_, reject) => {
          setTimeout(() => {
            clearInterval(pollingInterval)
            polling = false
            reject(new Error("任务超时"));
          }, timeoutMs);
        }),
      ]);
      console.log('result:{}', result)
      return result;
    } catch (error) {
      throw new Error("提交任务失败");
    }
  }

  /**
   * 反推
   * @param data
   */
  static interrogate(data: any): Promise<any> {
    return useRequest({
      url: "/stableDiffusionServer/interrogate",
      method: "post",
      data
    })
  }

  static getInterrogators(resourceId: string): Promise<any> {
    return useRequest({
      url: "/stableDiffusionServer/getInterrogators?resourceId=" + resourceId,
      method: "get"
    })
  }


  static getUpscaler(resourceId: string): Promise<any> {
    return useRequest({
      url: "/stableDiffusionServer/getUpscaler?resourceId=" + resourceId,
      method: "get"
    })
  }

  static getControlNetType(sdResourceId: string): Promise<any> {
    return useRequest({
      url: "/stableDiffusionServer/getControlNetType?resourceId=" + sdResourceId,
      method: "get"
    })
  }


  static controlNetDetect(data: any): Promise<any> {
    return useRequest({
      url: "/stableDiffusionServer/controlNetDetect",
      method: "post",
      data
    })
  }


  static refreshSDOption(resourceId: string): Promise<any> {
    return useRequest({
      url: "/stableDiffusionServer/refreshSDOption?resourceId=" + resourceId,
      method: "get"
    })
  }


  static generateText2Img(data: any): Promise<any> {
    return useRequest({
      url: "/stableDiffusionTask/submitTxt2ImgTask",
      method: "post",
      data
    })
  }


  static generateImg2Img(data: any): Promise<any> {
    return useRequest({
      url: "/stableDiffusionTask/img2img",
      method: "post",
      data
    })
  }


  static checkTask(taskId: string): Promise<any> {
    return useRequest({
      url: "/gps/sdTask/" + taskId + "/fetch",
      method: "get",
    })
  }

  static getChatState(): Promise<any> {
    return useRequest({
      url: "/chat_message/message/state",
      method: "post"
    })
  }

  static addStoryBoarPaintLog(storyBoardId: string, taskId: string): Promise<any> {
    return useRequest({
      url: "/storyBoard/addStoryPaintLog?storyBoardId=" + storyBoardId + "&taskId=" + taskId,
      method: "get"
    })
  }

  static async getTemplate(templateCode: string): Promise<any> {
    return useRequest({
      url: "/sdTemplate/getTemplate?templateCode=" + templateCode,
      method: "get"
    })
  }

  static async getControlNetConfig(controlNetType: string): Promise<any> {
    return useRequest({
      url: "../paint/controlnetConfig/" + controlNetType + ".json",
      method: "get"
    })
  }

  static getControlNetModuleInfo(data: any): Promise<any> {
    return useRequest({
      url: "/stableDiffusionServer/getControlNetModuleInfo",
      method: "post",
      params: data
    })
  }


  static async scannerModel(data: any): Promise<any> {
    return useRequest({
      url: "/civitai/searchModelImageFormLibOrCivitai",
      method: "post",
      data
    })
  }

  static uploadModelImage(data: any){
    return useRequest({
      url: "/stableDiffusionServer/uploadModelImage",
      method: "post",
      data
    })
  }

  static testPlugin(resourceId: string) {
    return useRequest({
      url: "/stableDiffusionServer/stableDiffusionPluginTest/"+resourceId,
      method: "get"
    })
  }
}
